﻿using MediatR;
using Medical.Api.Write.Application.Command.DepartmentManagement.Use;
using Medical.Domain.DepartmentInfo;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;
using System.Transactions;

namespace Medical.Api.Write.Application.Handler.DepartmentManagement.Use
{
    public class DeleteUseCommandHandler : IRequestHandler<DeleteUseCommands, ApiResult<int>>
    {
        private readonly IBaseRepository<UseTable> useRep;
        private readonly ILogger<DeleteUseCommandHandler> logger;

        public DeleteUseCommandHandler(IBaseRepository<UseTable> useRep, ILogger<DeleteUseCommandHandler> logger)
        {
            this.useRep = useRep;
            this.logger = logger;
        }

        public async Task<ApiResult<int>> Handle(DeleteUseCommands request, CancellationToken cancellationToken)
        {
            try
            {
                //开启事务
                using (var tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    try
                    {
                        var useid = useRep.GetModel(request.UseId);
                        useid.IsDeleted = true;
                        useRep.Update(useid);

                        //提交事务
                        tran.Complete();
                        return new ApiResult<int>
                        {
                            Code=ApiEnums.Success,
                            Data=1,
                            Msg="使用表删除成功!"
                        };
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
